﻿using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using Autofac;
using Autofac.Integration.Mvc;

namespace TT.Web.Hubs
{
    public class Match : Hub
    {       
        private readonly Logic.Interfaces.ITTContext _dbContext;
        private readonly Logic.Interfaces.ITournamentGenerator _tournamentGenerator;

        public Match() {
            var lifetimeScope = AutofacDependencyResolver.Current.RequestLifetimeScope;
            _dbContext = lifetimeScope.Resolve<Logic.Interfaces.ITTContext>();
            _tournamentGenerator = lifetimeScope.Resolve<Logic.Interfaces.ITournamentGenerator>();
        }

        /// <summary>
        /// Updates score
        /// </summary>
        /// <param name="id">id of the match</param>
        /// <param name="newScore">new match score</param>
        /// <param name="isHome">is new score home or away score</param>
        public void UpdateScore(int id, int newScore, bool isHome)
        {
            var match = _dbContext.Matches.FirstOrDefault(x => x.Id == id);

            var isFinished = match.IsFinished();

            if (!isFinished)
            {
                if (isHome)
                {
                    match.HomeScore = newScore;
                    _dbContext.Entry(match).Property(x => x.HomeScore).IsModified = true;

                }
                else
                {
                    match.AwayScore = newScore;
                    _dbContext.Entry(match).Property(x => x.AwayScore).IsModified = true;
                }

                _dbContext.SaveChanges();
                
                isFinished = match.IsFinished();
                if (isFinished)
                {
                    //make sure score is not greater than allowed - 
                    //re-set score if game is finished
                    //TODO: improve it...
                    if (isHome)
                    {
                        newScore = match.HomeScore;
                    }
                    else
                    {
                        newScore = match.AwayScore;
                    }

                    //progress
                    var tournament = (from t in _dbContext.Tournaments
                    .Include("Rounds.Matches.HomePlayer1")
                    .Include("Rounds.Matches.AwayPlayer1")
                                      from r in t.Rounds
                                      from m in r.Matches
                                      where m.Id == match.Id
                                      select t).FirstOrDefault();
                    var progressResult =
                        _tournamentGenerator.ProgressWinnerToNextRound(match, tournament);
                    if (progressResult != null)
                    {
                        Clients.All.updatePlayer(progressResult.MatchId,
                            progressResult.PlayerFirstName, progressResult.IsHome);
                    }
                }

                Clients.All.updateScore(id, newScore, isHome, isFinished);
            }


            //return Json(
            //    new
            //    {
            //        isFinished = isFinished,
            //        matchId = id,
            //        newScore = newScore,
            //        isHome = isHome
            //    }, JsonRequestBehavior.AllowGet);
        }
    }
}